<template>
  <div class="test-report-container">
    <el-card class="report-card">
      <!-- 上半部分：报告概览 -->
      <div class="report-header">
        <h2>报告概览</h2>
      </div>

      <el-row :gutter="20" class="stats-row">
        <el-col :xs="12" :sm="6" v-for="stat in stats" :key="stat.label">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-card shadow="never" class="info-card">
        <el-descriptions title="测试计划信息" :column="2" border>
          <el-descriptions-item label="测试计划">{{ testPlan.title || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <dict-tag :options="dict.type.test_plan_status" :value="testPlan.status"/>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            <user-and-avatar :user-id="testPlan.assignee"/>
          </el-descriptions-item>
          <el-descriptions-item label="关联项目ID">{{ testPlan.projectId || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="测试计划类型">
            <dict-tag :options="dict.type.test_plan_type" :value="testPlan.testPlanType"/>
          </el-descriptions-item>
          <el-descriptions-item label="更新人">
            <user-and-avatar :user-id="testPlan.updatedBy"/>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ testPlan.createdAt || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ testPlan.updatedAt || '未设置' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card shadow="never" class="chart-card">
        <h3>执行结果分布</h3>
        <div class="chart-container">
          <div class="pie-chart" ref="pieChart"></div>
          <el-table :data="resultData" style="width: 100%">
            <el-table-column prop="result" label="结果" width="180">
              <template #default="{row}">
                <el-tag :type="getTagType(row.result)">{{ row.result }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="用例数" width="180"/>
            <el-table-column prop="percentage" label="占比"/>
          </el-table>
        </div>
      </el-card>

      <!-- 下半部分：成员执行情况 -->
      <el-card shadow="never" class="defect-card">
        <h3>成员执行情况</h3>
        <div class="chart-container">
          <div class="bar-chart" ref="barChart"></div>
          <el-table :data="moduleData" style="width: 100%">
            <el-table-column prop="name" label="成员" width="180"/>
            <el-table-column label="未执行">
              <template #default="{row}">{{ row.notExecuted }}</template>
            </el-table-column>
            <el-table-column label="已执行">
              <template #default="{row}">{{ row.executed }}</template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {allInit} from "@/api/projectUser/userTestPlan";
import UserAndAvatar from "@/components/UserAndAvatar/index.vue";
import {getDicts} from "@/api/system/dict/data";
import {getUserAvatar} from "@/utils/userAndAvatar";

export default {
  name: "TestReport",
  components: {UserAndAvatar},
  dicts: ['test_plan_type', 'test_plan_status'],
  props: {
    testPlanId: [Number, String]
  },
  data() {
    return {
      testPlan: {},
      testSteps: [],
      tests: [],
      flaws: [],
      resultData: [],
      moduleData: [],
      testStatusType: [],
    };
  },
  computed: {
    stats() {
      let stats = []
      stats.push({value: this.tests.length, label: '用例数'})
      let startTest = 100 - (this.tests.filter(test => test.outcome == null || test.outcome === '').length * 100 / this.tests.length);
      stats.push({value: parseInt(startTest) + '%', label: '用例覆盖率'})
      let pass = (this.tests.filter(test => test.outcome === 'pass').length * 100 / this.tests.length);
      stats.push({value: parseInt(pass) + '%', label: '用例通过率'})
      stats.push({value: this.flaws.length, label: '缺陷数'})
      return stats
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData() {
      let res = await allInit(this.testPlanId)
      this.testPlan = res.data.testPlan;
      this.testSteps = res.data.testSteps;
      this.tests = res.data.tests;
      this.flaws = res.data.flaws;

      // 这里处理API返回的数据

      // 更新图表数据
      let response = await getDicts("test_outcome")
      this.testStatusType = response.data;
      let resultData = []
      response.data.forEach(item => {
        let count = this.tests.filter(test => test.outcome === item.dictValue).length;
        let percentage = (count / this.tests.length * 100).toFixed(2) + '%';
        resultData.push({result: item.dictLabel, count: count, percentage: percentage})
      });
      this.resultData = resultData;

      console.log(this.tests);
      let moduleData = new Map()
      for (const item of this.tests) {
        console.log("item",item);
        if (!moduleData.has(item.executorId)) {
          let userAvatar = await getUserAvatar(item.executorId);
          console.log(userAvatar);
          moduleData.set(item.executorId, {name: (userAvatar || {}).userName||"未指定", notExecuted: 0, executed: 0})
        }
        if (item.outcome === 'untested') {
          moduleData.get(item.executorId).notExecuted++
        } else {
          moduleData.get(item.executorId).executed++
        }
      }
      this.moduleData = Array.from(moduleData.values())
      console.log(this.moduleData);
      this.updateCharts();
    },
    updateCharts() {
      // 饼图配置
      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.resultData.map(item => item.result)
        },
        series: [
          {
            name: '执行结果',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.resultData.map(item => ({
              value: item.count,
              name: item.result,
              itemStyle: {color: this.getChartColor(item.result)}
            }))
          }
        ]
      };
      echarts.init(this.$refs.pieChart).setOption(pieOption);

      // 柱状图配置
      const barOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01],
          max: 12,
          interval: 3
        },
        yAxis: {
          type: 'category',
          data: this.moduleData.map(item => item.name || '未指定')
        },
        series: [
          {
            name: '未完成',
            type: 'bar',
            data: this.moduleData.map(item => item.notExecuted),
            itemStyle: {
              color: '#F56C6C'
            }
          },
          {
            name: '完成',
            type: 'bar',
            data: this.moduleData.map(item => item.executed),
            itemStyle: {
              color: '#2ddd63'
            }
          }
        ]
      };
      echarts.init(this.$refs.barChart).setOption(barOption);
    },
    getTagType(result) {
      const types = {
        '通过': 'success',
        '失败': 'danger',
        '未测': 'info',
        '受阻': 'warning',
        '跳过': ''
      };
      return types[result] || '';
    },
    getChartColor(result) {
      const colors = {
        '通过': '#67C23A',
        '失败': '#F56C6C',
        '未测': '#409EFF',
        '受阻': '#E6A23C',
        '跳过': '#909399'
      };
      return colors[result] || '#909399';
    }
  }
};
</script>

<style scoped>
.test-report-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.report-time {
  color: #909399;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.info-card, .chart-card, .member-card, .defect-card {
  margin-bottom: 20px;
}

.chart-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.pie-chart, .bar-chart {
  width: 400px;
  height: 300px;
}

.report-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.page-indicator {
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .chart-container {
    flex-direction: column;
  }

  .pie-chart, .bar-chart {
    width: 100%;
    height: 250px;
  }

  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .report-time {
    margin-top: 5px;
  }
}
</style>
